package com.inibb.app.dao.sqlt;

import java.io.File;
import java.util.List;

import org.apache.commons.collections.Transformer;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SqltTransformer implements Transformer{

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private File[] files;
	
	private String type;
	
	public SqltTransformer(File[] files, String type){
		this.files = files;
		this.type = type;
	}
	@Override
	public Object transform(Object input) {
		
		String keyx = (String)input;
		try {
			logger.debug(keyx);
			return getSqlt(keyx);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private String getSqlt(String keyx) throws Exception{
		String[] strs = StringUtils.split(keyx, "_");
		String namespace = StringUtils.trim(strs[0]);
		//String sqlid = strs[1];
		for(File f:files){
			
			if(("sqlt-"+namespace+".xml").equals(f.getName())){
				logger.debug("reading file "+f.getName());
				SAXReader reader = new SAXReader();
			    Document tdoc = reader.read(f);

				Element root = tdoc.getRootElement();
				
				if(type.equals("jpqls")){
					Element element = root.element("jpqls");
					if(element!=null){
						List<Element> jpqlElements = element.elements("sqlt");
	
						for(Element e: jpqlElements){
							String key = namespace+"_"+e.attributeValue("id");
							if(keyx.equals(key)){								
								return e.getText();
							}
						}
						
					}else{
					}
				
				}
				if(type.equals("sqls")){
					Element element2 = root.element("sqls");
					if(element2!=null){
						List<Element> sqlElements = element2.elements("sqlt");
						for(Element e: sqlElements){
							String key = namespace+"_"+e.attributeValue("id");
							if(keyx.equals(key)){								
								return e.getText();
							}
						}
					}else{
					}
				}
				break;
			}
		}
		
		return null;
		
	}
}
